package com.shi.controller;

import cn.hutool.core.bean.BeanUtil;
import com.shi.common.Result;
import com.shi.entity.dto.AccountEmailLoginDto;
import com.shi.entity.dto.AccountUsernameLoginDto;
import com.shi.entity.po.Account;
import com.shi.entity.vo.SessionAccountVO;
import com.shi.properties.SysProperties;
import com.shi.service.AccountService;
import com.shi.service.MenuService;
import com.shi.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.UUID;

import static com.shi.constants.RedisConstant.DATA_TTL;
import static com.shi.constants.RedisConstant.LOGIN_TOKEN_KEY;
import static com.shi.constants.SysConstant.TOKEN_KEY;

@Api(tags = "登录、登出功能")
@RestController
@RequestMapping
public class LoginController {

    @Resource
    private AccountService accountService;

    @Resource
    private MenuService menuService;

    @Resource
    private SysProperties sysProperties;

    @ApiOperation("用户名登录")
    @PostMapping("/login/username")
    public Result usernameLogin(HttpServletResponse response, @RequestBody @Valid AccountUsernameLoginDto accountUsernameLoginDto) {
        Account account = accountService.usernameLogin(accountUsernameLoginDto);
        handlePermission(response, account);
        return Result.ok();
    }


    @ApiOperation("邮箱登录")
    @PostMapping("/login/email")
    public Result emailLogin(HttpServletResponse response, @RequestBody @Valid AccountEmailLoginDto accountEmailLoginDto) {
        Account account = accountService.emailLogin(accountEmailLoginDto);
        handlePermission(response, account);
        return Result.ok();
    }

    private void handlePermission(HttpServletResponse response,Account account){
        SessionAccountVO sessionAccountVO;
        // 登录成功封装用户信息
        sessionAccountVO = BeanUtil.toBean(account, SessionAccountVO.class);
        // 判断是否是超级管理员
        if (sysProperties.getSysAdminList().contains(account.getUsername())) {
            sessionAccountVO.setIsAdmin(true);
            // 全部权限码
            sessionAccountVO.setPermissionCodeList(menuService.queryAllMenuCode());
        } else {
            // 指定用户的权限码
            sessionAccountVO.setPermissionCodeList(menuService.queryMenuCodeByAccountId(account.getUid()));
        }
        handleCookie(response,sessionAccountVO);
    }
    private void handleCookie(HttpServletResponse response,SessionAccountVO sessionAccountVO){
        String token= UUID.randomUUID().toString();
        RedisUtil.set(LOGIN_TOKEN_KEY+token,sessionAccountVO,DATA_TTL);
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    @ApiOperation("用户退出")
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String token=null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (TOKEN_KEY.equals(cookie.getName())) {
                    token = cookie.getValue();
                    cookie.setMaxAge(0);
                    break;
                }
            }
            if (token != null) {
                RedisUtil.delete(LOGIN_TOKEN_KEY+token);
            }
        }
        return Result.ok();
    }
}
